const {ccclass, property} = cc._decorator;


@ccclass
export default class ImageLoader extends cc.Component {

    
    spriteFrame: cc.SpriteFrame = null;

    onLoad() {
        this.setupSpriteFrame();
    }


    /**设置图片 */
    setupSpriteFrame(){
        if(this.spriteFrame){
            const spr = this.getComponent(cc.Sprite);
            if(spr){
                spr.spriteFrame = this.spriteFrame;
            }
        }
    }

    /**根据用户ID获取头像并显示 */
    setUserID(userId?){

        if(cc.sys.isNative == false){
            return;
        }

        if(!userId){
            return;
        }

        if(cc.vv.images == null){
            cc.vv.images = {};
        }

        getBaseInfo(userId, (code, info) => {
            if(info && info.url){
                loadImage(info.url, userId, (err, spriteFrame) => {
                    this.spriteFrame = spriteFrame;
                    this.setupSpriteFrame();
                });
            }
        });
    }
}


function loadImage(url, code, callback){
    cc.loader.load(url, (err, tex) => {
        const spriteFrame = new cc.SpriteFrame(tex, new cc.Rect(0, 0, tex.width, tex.height));
        callback(code, spriteFrame);
    });
}

function getBaseInfo(userId, callback){

    if(cc.vv.baseInfoMap == null){
        cc.vv.baseInfoMap = {};
    }

    if(cc.vv.baseInfoMap[userId] != null){
        callback(userId, cc.vv.baseInfoMap[userId]);
    }
    else{
        cc.vv.http.sendRequest('/base_info', {userId}, (ret: cc.ret) => {
            let url = null;
            if(ret.headimgurl){
                url = ret.headimgurl + '.jpg';
            }
            let info: cc.ret = {
                name: ret.name,
                sex: ret.sex,
                url: url,
            };
            cc.vv.baseInfoMap[userId] = info;
            callback(userId, info);
        }, cc.vv.http.master_url);
    }
}
